package com.wtcrazy.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.wtcrazy.utils.JwtUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//token拦截器
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = "";
        if (!request.getMethod().equals("OPTIONS")) {
            token = request.getHeader("Authroniation");
        }
        log.info("请求头中的token是:------------{}", token);
        if (JwtUtil.checkToken(token) != 1) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");//让浏览器识别返回的是json
            try {
                JSONObject json = new JSONObject();
                json.put("msg", "token verify fail");
                json.put("code", "50000");
                json.put("result", false);
                response.getWriter().append(json.toJSONString());//转成json写过去
                System.out.println("认证失败，未通过token拦截器");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return false;
        }
        System.out.println("通过token拦截器");
        return true;
    }
}
